package com.util.mybatisgenerator;

import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.internal.DefaultCommentGenerator;
import org.mybatis.generator.internal.util.StringUtility;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 自定义mybatis注释插件
 * @author zhouquan
 * @date 2018-01-31
 *
 */
public class RemarksCommentPlugin extends DefaultCommentGenerator {
	
	/**
	 * 实体类添加注释
	 */
	@Override  
    public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {  
        topLevelClass.addJavaDocLine("/**");  
        topLevelClass.addJavaDocLine(" * @tableName "+introspectedTable.getFullyQualifiedTable());  
        topLevelClass.addJavaDocLine(" * @date "+new SimpleDateFormat("yyyy-MM-dd").format(new Date()));  
        topLevelClass.addJavaDocLine(" * @author by:zhouquan ");
        topLevelClass.addJavaDocLine(" */");  
    }  
	
	/**
	 * 字段添加注释
	 */
    public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {  
        String remark = introspectedColumn.getRemarks();  
        String columnName = introspectedColumn.getActualColumnName();  
        List<IntrospectedColumn> primaryKey = introspectedTable.getPrimaryKeyColumns();  
        for (IntrospectedColumn pk : primaryKey) {  
            if(columnName.equals(pk.getActualColumnName())){  
                remark +=" (主健ID)";  
                continue;   //主健属性上无需生明可选项跟必填项介绍  
            }  
            if (StringUtility.stringHasValue(remark)) {  
                remark += introspectedColumn.isNullable() ? "(可选项)" : "(必填项)";  
            }  
        }  
        String defaultValue = introspectedColumn.getDefaultValue();  
        remark += null != defaultValue ? "  (默认值为: "+defaultValue+")" : " ";  
        field.addJavaDocLine("/** "+ remark+" */");  
    }  

}
